// 220110 2057

// 通过 EventEmitter 处理分发的请求

var http = require('http');
var url = require('url');
// const { exit } = require('process');
var events = require('events');

var eventEmitter = new events.EventEmitter();

// route 根路径
eventEmitter.on('/', function(method, response) {
	response.writeHead(200, {'Content-Type': "text/plain; charset=utf-8"});
	response.end('root: ' + new Date());
});

// route 404
eventEmitter.on('404', function(method, url, response) {
	response.writeHead(200, {'Content-Type': "text/plain; charset=utf-8"});
	response.end('404 Not Found\n' + new Date());
});

http.createServer(function (req, resp) {
	console.log(req.url);
	
	// 分发请求
	if (eventEmitter.listenerCount(req.url) > 0) {
		eventEmitter.emit(req.url, req.method, resp);
	} else {
		eventEmitter.emit('404', req.method, req.url, resp);
	}
}).listen(8888);

console.log('服务器在 8888 端口启动');
